import Vue from 'vue';

export default ({
    content = () => {},
    data = {},
    props = {},
    on = {},
    confirm = () => {}
} = {}) => {
    return new Promise((resolve, reject) => {
        const dialog = new Vue({
            data() {
                return {
                    ...data,
                    visible: true,
                }
            },
            mounted() {
                this.$nextTick(() => {
                    this.$el?.focus?.();
                })
            },
            methods: {
                close() {
                    this.visible = false;
                    setTimeout(() => {
                        this.$el?.remove();
                    }, 500);
                },
                async confirm() {
                    if (await confirm(this)) {
                        return;
                    }
                    resolve();
                    this.close();
                }
            },
            render(h) {
                const contentDom = content?.(h, this) || content || '';
                return (
                    <div tabindex="1">
                        <el-dialog
                            class="v-dialog"
                            center
                            ref="dialog"
                            { ...{
                                props,
                                on
                            } }
                            visible={this.visible}
                            onClose={this.close}
                        >
                            { contentDom }
                            <div slot='footer' class="v-dialog__footer" style="text-align: right;">
                                <el-button onClick={this.close}>取 消</el-button>
                                <el-button type="primary" onClick={this.confirm}>确 定</el-button>
                            </div> 
                        </el-dialog>
                    </div> 
                )
            }
        }).$mount();

        document.body.appendChild(dialog.$el);
    });
}